package com.blog.dao.impl;

import com.blog.dao.BaseDao;
import com.blog.dao.CommentDao;
import com.blog.pojo.Article;
import com.blog.pojo.Comment;
import com.blog.utils.SqlIUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDaoImpl extends BaseDao implements CommentDao {

    @Override
    public List<Comment> findCommentsByArticleId(int article_id) {
        List<Comment> commentList=new ArrayList<Comment>();
        try {
            String sql = "select * from tb_comment where article_id=? ORDER BY star DESC";
            ResultSet resultSet = this.execQuery(sql, new Object[]{article_id});
            while (resultSet.next()) {
                int id = resultSet.getInt(1);
                article_id = resultSet.getInt(2);
                String nickname = resultSet.getString(3);
                String content = resultSet.getString(4);
                String time = resultSet.getString(5);
                Integer star = resultSet.getInt(6);
                Integer diss = resultSet.getInt(7);
                Comment coment = new Comment(id, article_id, nickname, content, time, star, diss);
                commentList.add(coment);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConn(conn, resultSet, ps);
        }
        return commentList;
    }

    @Override
    public int add(Comment comment) {
        if(SqlIUtils.isSqlValid(comment.getContent()+" "+comment.getTime()+" "+comment.getNickname())){
            return 0;
        }
        String sql="insert into tb_comment values(null,?,?,?,?,?,?)";
        Object[] parms={comment.getArticle_id(),comment.getNickname(),comment.getContent(),comment.getTime(),comment.getStar(),comment.getDiss()};
        return this.execUpdate(sql,parms);
    }

    @Override
    public int deleteById(String commentId) {
        if(SqlIUtils.isSqlValid(commentId)){
            return 0;
        }
        String sql="delete from tb_comment where id=?";
        Object[] parms={commentId};
        return this.execUpdate(sql,parms);
    }

    @Override
    public int starById(String commentId) {
        if(SqlIUtils.isSqlValid(commentId)){
            return 0;
        }
        String sql="update tb_comment set star=star+1 where id=?";
        Object[] parms={commentId};
        return this.execUpdate(sql,parms);
    }

    @Override
    public int dissById(String commentId) {
        if(SqlIUtils.isSqlValid(commentId)){
            return 0;
        }
        String sql="update tb_comment set diss=diss+1 where id=?";
        Object[] parms={commentId};
        return this.execUpdate(sql,parms);
    }
}
